package com.viknix.threadpool.manager.cluster.config;

import com.viknix.threadpool.manager.server.dependence.util.EnvUtil;
import io.jsonwebtoken.io.Decoders;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import java.util.Objects;

/**
 * @Author: Dongqi
 * @Date: 2021/11/18 10:10
 * @Version 1.0
 * @Description: 认证相关配置。
 */
@Configuration
public class AuthConfigs {

    private static Boolean cachingEnabled = null;

    /**
     * secret key.
     */
    @Value("${tpm.core.auth.default.token.secret.key:}")
    private String secretKey;

    /**
     * secret key byte array.
     */
    private byte[] secretKeyBytes;

    /**
     * Token validity time(seconds).
     */
    @Value("${tpm.core.auth.default.token.expire.seconds:18000}")
    private long tokenValidityInSeconds;

    /**
     * Which auth system is in use.
     */
    @Value("${tpm.core.auth.system.type:}")
    private String tpmAuthSystemType;

    @Value("${tpm.core.auth.server.identity.key:}")
    private String serverIdentityKey;

    @Value(("${tpm.core.auth.server.identity.value:}"))
    private String serverIdentityValue;

    @Value(("${tpm.core.auth.enable.userAgentAuthWhite:true}"))
    private boolean enableUserAgentAuthWhite;

    public byte[] getSecretKeyBytes() {
        if (secretKeyBytes == null) {
            secretKeyBytes = Decoders.BASE64.decode(secretKey);
        }
        return secretKeyBytes;
    }

    public long getTokenValidityInSeconds() {
        return tokenValidityInSeconds;
    }

    public String gettpmAuthSystemType() {
        return tpmAuthSystemType;
    }

    public String getServerIdentityKey() {
        return serverIdentityKey;
    }

    public String getServerIdentityValue() {
        return serverIdentityValue;
    }

    public boolean isEnableUserAgentAuthWhite() {
        return enableUserAgentAuthWhite;
    }

    /**
     * auth function is open.
     *
     * @return auth function is open
     */
    public boolean isAuthEnabled() {
        // Runtime -D parameter has higher priority:
        String enabled = System.getProperty("tpm.core.auth.enabled");
        if (StringUtils.isNotBlank(enabled)) {
            return BooleanUtils.toBoolean(enabled);
        }
        return BooleanUtils
                .toBoolean(EnvUtil.getProperty("tpm.core.auth.enabled", "false"));
    }

    /**
     * Whether permission information can be cached.
     *
     * @return bool
     */
    public boolean isCachingEnabled() {
        if (Objects.nonNull(AuthConfigs.cachingEnabled)) {
            return cachingEnabled;
        }
        return BooleanUtils
                .toBoolean(EnvUtil.getProperty("tpm.core.auth.caching.enabled", "true"));
    }
}
